package com.woniu.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.woniu.entity.*;
import com.woniu.service.IAssetChannelService;
import com.woniu.service.ICapitalChannelService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @description: 用于处理渠道模块请求的controller
 * @author Dante
 * @date: 2022/9/20 19:18
 */
@Api(value = "渠道控制器", tags = {"渠道"})
@RestController
@RequestMapping("/channel")
public class ChannelController extends BaseController {
    @Autowired
    ICapitalChannelService capitalChannelService;

    @Autowired
    IAssetChannelService assetChannelService;

    /**
     * @description: 查询所有资金渠道信息
     * @param: []
     * @return: com.ruoyi.common.core.page.TableDataInfo
     * @author Dante
     * @date: 2022/9/21 16:58
     */
    @ApiOperation(value = "查询所有资金渠道",notes = "根据渠道类型查询所有资金渠道",
            response=CapitalChannelEntity.class, responseContainer="List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/listCapitalChannel")
    public TableDataInfo findAll(){
        startPage();
        List<CapitalChannelEntity> capitalChannelEntity = capitalChannelService.findAll();
        return getDataTable(capitalChannelEntity);
    }

    @ApiOperation(value = "查询所有资产渠道",notes = "根据渠道类型查询所有资产渠道",
            response=CapitalChannelEntity.class, responseContainer="List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @PreAuthorize("@ss.hasPermi('channel:assetChannel')")
    @GetMapping("/listAssetChannel")
    public TableDataInfo findAllAssetChannel(){
        startPage();
        List<CapitalChannelEntity> assetChannels = assetChannelService.findAllAssetChannel();
        assetChannels.forEach((e)->{
            e.setProductionName(e.getProducts().get(0).getProductionName());
        });
        return getDataTable(assetChannels);
    }

    @ApiOperation(value = "查询所有产品",
            response=ProductionInfo.class, responseContainer="List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @PreAuthorize("@ss.hasPermi('channel:assetChannel')")
    @GetMapping("/listCapitalProductions")
    public TableDataInfo listCapitalProductions(){
        startPage();
        List<ProductionInfo> capitalProductions = assetChannelService.listCapitalProductions();
        return getDataTable(capitalProductions);
    }

    /**
     * @description: 查询所有用户信息
     * @param: []
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 17:59
     */
    @ApiOperation(value = "查询客户信息",
            response=SysAdminVO.class, responseContainer="List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/getAllUserInfo")
    public AjaxResult getAllUserInfo(){
        List<SysAdminVO> findResult = capitalChannelService.getAllUserInfo();
        return new AjaxResult(HttpStatus.SUCCESS,"获取所有用户信息成功",findResult);
    }

    /**
     * @description: 查询当前登录用户信息
     * @param: [userName]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 17:59
     */
    @ApiOperation(value = "查询当前登录用户信息",
            response=SysAdminVO.class, httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "userName",value="客户姓名",required=true,dataTypeClass=String.class,paramType="path"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/findCurrentUser/{data}")
    public AjaxResult findCurrentUser(@PathVariable("data") String userName){
        SysAdminVO findResult = capitalChannelService.findCurrentUser(userName);
        return new AjaxResult(HttpStatus.SUCCESS,"获取当前用户信息成功",findResult);
    }

    /**
     * @description: 更新渠道状态
     * @param: [channelId]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 18:41
     */
    @ApiOperation(value = "更新渠道状态",
            response=AjaxResult.class, httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "channelId",value="渠道id",required=true,dataTypeClass=Integer.class,paramType="path"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/updateChannelStatus/{data}")
    public AjaxResult updateChannelStatus(@PathVariable("data") Integer channelId){
        Boolean updateResult = capitalChannelService.updateChannelStatus(channelId);
        if (updateResult){
            return new AjaxResult(HttpStatus.SUCCESS,"修改成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"修改失败",null);
        }
    }

    /**
     * @description: 禁用当前渠道
     * @param: [channelId]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 18:41
     */
    @ApiOperation(value = "禁用当前渠道",
            response=AjaxResult.class, httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "channelId",value="渠道id",required=true,dataTypeClass=Integer.class,paramType="path"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/banChannel/{channelId}")
    public AjaxResult banChannel(@PathVariable("channelId") Integer channelId){
        Boolean updateResult = capitalChannelService.banChannel(channelId);
        if (updateResult){
            return new AjaxResult(HttpStatus.SUCCESS,"修改成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"修改失败",null);
        }
    }

    /**
     * @description: 查询单个渠道信息
     * @param: [channelId]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 18:41
     */
    @ApiOperation(value = "查询单个渠道信息",
            response=AjaxResult.class, httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "channelId",value="渠道id",required=true,dataTypeClass=Integer.class,paramType="path"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/checkChannelInfo/{data}")
    public AjaxResult checkChannelInfo(@PathVariable("data") Integer channelId){
        CapitalChannelEntity channelInfo = capitalChannelService.checkChannelInfo(channelId);
        if(Objects.nonNull(channelInfo)){
            return new AjaxResult(HttpStatus.SUCCESS,"获取渠道详情成功",channelInfo);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"查询失败",null);
        }
    }


    /**
     * @description: 查询单个渠道信息相关的产品
     * @param: [channelId]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 18:41
     */
    @ApiOperation(value = "查询单个渠道信息相关的产品",
            response=ProductionInfo.class, responseContainer = "List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "channelId",value="渠道id",required=true,dataTypeClass=Integer.class,paramType="path"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/getAllRelativeProducts/{channelId}")
    public AjaxResult getAllRelativeProducts(@PathVariable("channelId") Integer channelId){
        List<ProductionInfo> channelProductionInfo = assetChannelService.getAllRelativeProducts(channelId);
        if(Objects.nonNull(channelProductionInfo) && channelProductionInfo.size()>0){
            return new AjaxResult(HttpStatus.SUCCESS,"查询相关代理产品成功",channelProductionInfo);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"查询失败",null);
        }
    }

    /**
     * @description: 取消单个渠道代理的某个产品（删除中间表数据）
     * @param: [cpmId]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 18:41
     */
    @ApiOperation(value = "取消单个渠道代理的某个产品",
            response=AjaxResult.class, httpMethod="DELETE",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "cpmId",value="渠道产品中间表id",required=true,dataTypeClass=Integer.class,paramType="path"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @DeleteMapping("/deleteRelProduct/{cpmId}")
    public AjaxResult deleteRelProduct(@PathVariable("cpmId") Integer cpmId){
        Boolean deleteResult = assetChannelService.deleteRelProduct(cpmId);
        if(deleteResult){
            return new AjaxResult(HttpStatus.SUCCESS,"取消代理成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"取消代理失败",null);
        }
    }

    /**
     * @description: 复合查询资金渠道的信息，带分页
     * @param: [data]
     * @return: com.ruoyi.common.core.page.TableDataInfo
     * @author Dante
     * @date: 2022/9/21 16:58
     */
    @ApiOperation(value = "复合查询资金渠道的信息",
            response=CapitalChannelEntity.class, responseContainer = "List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="查询数据",required=true,dataTypeClass=CapitalChannelSearchVO.class))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/searchCapitalChannel")
    @ResponseBody
    public TableDataInfo searchCapitalChannel( CapitalChannelSearchVO data){
        startPage();
        List<CapitalChannelEntity> capitalChannelEntity = capitalChannelService.searchWithLimits(data);
        return getDataTable(capitalChannelEntity);
    }

    @ApiOperation(value = "复合查询资产渠道的信息",
            response=CapitalChannelEntity.class, responseContainer = "List", httpMethod="GET",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="查询数据",required=true,dataTypeClass=CapitalChannelSearchVO.class))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @GetMapping("/searchAssetChannel")
    @ResponseBody
    public TableDataInfo searchAssetChannel( CapitalChannelSearchVO data){
        startPage();
        List<CapitalChannelEntity> assetChannels= assetChannelService.searchWithLimits(data);
        return getDataTable(assetChannels);
    }

    /**
     * @description: 添加资金渠道
     * @author Dante
     * @date: 2022/9/22 10:52
     */
    @ApiOperation(value = "添加资金渠道",
            response=AjaxResult.class, httpMethod="POST",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="添加的数据",required=true,dataTypeClass=CapitalChannelEntity.class,paramType="body"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @PostMapping("/addCapitalChannel")
    @ResponseBody
    public AjaxResult addCapitalChannel(@RequestBody CapitalChannelEntity data){
        Boolean insertResult = capitalChannelService.addCapitalChannel(data);
        if (insertResult){
            return new AjaxResult(HttpStatus.SUCCESS,"新增成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"新增失败",null);
        }

    }

    /**
     * @description: 添加资产渠道
     * @author Dante
     * @date: 2022/9/22 10:52
     */
    @ApiOperation(value = "添加资产渠道",
            response=AjaxResult.class, httpMethod="POST",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="添加的数据",required=true,dataTypeClass=CapitalChannelEntity.class,paramType="body"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @PostMapping("/addAssetChannel")
    @ResponseBody
    public AjaxResult addAssetChannel(@RequestBody CapitalChannelEntity data){
        Boolean insertResult = assetChannelService.addAssetChannel(data);
        if (insertResult){
            return new AjaxResult(HttpStatus.SUCCESS,"新增成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"渠道名重复，新增失败",null);
        }

    }

    /**
     * @description: 添加产品到资产渠道
     * @author Dante
     * @date: 2022/9/22 10:52
     */
    @ApiOperation(value = "添加产品到资产渠道",
            response=AjaxResult.class, httpMethod="POST",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="添加的数据",required=true,dataTypeClass=Map.class,paramType="body"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @PostMapping("/addProductToChannel")
    @ResponseBody
    public AjaxResult addProductToChannel(@RequestBody Map<String,Object> data){
        Boolean insertResult = assetChannelService.addProductToChannel(data);
        if (insertResult){
            return new AjaxResult(HttpStatus.SUCCESS,"添加产品成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"已经存在产品信息，添加失败",null);
        }

    }

    /**
     * @description: 查询关联产品
     * @author Dante
     * @date: 2022/9/22 10:52
     */
    @ApiOperation(value = "查询关联产品",
            response=ProductionInfo.class, responseContainer = "List", httpMethod="POST",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="查询的数据",required=true,dataTypeClass=Map.class,paramType="body"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @PostMapping("/searchRelProduct")
    @ResponseBody
    public AjaxResult searchRelProduct(@RequestBody Map<String,Object> data){
        Map<String,Object> temp = new HashMap<>(2);

        if(!(isContainChinese((String) data.get(KeyWords.SEARCH_RELATIVE_PRODUCT_INFO)))){
            temp.put("productionCode",data.get(KeyWords.SEARCH_RELATIVE_PRODUCT_INFO));
        }else{
            temp.put("productionName",data.get(KeyWords.SEARCH_RELATIVE_PRODUCT_INFO));
        }

        List<ProductionInfo> searchResult = assetChannelService.searchRelProduct(temp);
        if (Objects.nonNull(searchResult) && searchResult.size()>0){
            return new AjaxResult(HttpStatus.SUCCESS,"查询产品成功",searchResult);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"查询失败，请稍后再试",null);
        }

    }


    /**
     * @description: 更新资金渠道信息
     * @param: [data]
     * @return: com.ruoyi.common.core.domain.AjaxResult
     * @author Dante
     * @date: 2022/9/22 18:42
     */
    @ApiOperation(value = "更新资金渠道信息",
            response=AjaxResult.class, httpMethod="POST",
            produces="application/json",code=200,tags = {"渠道"})
    @ApiImplicitParams(@ApiImplicitParam(name = "data",value="更新的数据",required=true,dataTypeClass=CapitalChannelEntity.class,paramType="body"))
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @PostMapping("/updateCapitalChannel")
    @ResponseBody
    public AjaxResult updateCapitalChannel(@RequestBody CapitalChannelEntity data){
        Boolean insertResult = capitalChannelService.updateCapitalChannel(data);
        if (insertResult){
            return new AjaxResult(HttpStatus.SUCCESS,"修改成功",null);
        }else {
            return new AjaxResult(HttpStatus.ERROR,"修改失败",null);
        }

    }

    /**
     * @description: 导出选中的行的渠道信息
     * @param: [response, data]
     * @return: void
     * @author Dante
     * @date: 2022/9/21 16:57
     */
    @ApiOperation(value = "导出选中的行的渠道信息",notes = "根据用户选择的对应行导出所有渠道信息",
            response=void.class, httpMethod="POST",
            produces="application/json",code=200,tags = {"渠道"})
    @PreAuthorize("@ss.hasPermi('channel:capitalChannel')")
    @PostMapping("/exportChosen")
    @ResponseBody
    public void export(HttpServletResponse response,CapitalChannelExportVO data) throws IOException {
        String finalFileName = "";
        List<CapitalChannelEntity> list = null;
        if(KeyWords.CAPITAL_CHANNEL_TYPE.equals(data.getChannelType())){
            finalFileName = KeyWords.EXPORT_CAPITAL_NAME;
            list = capitalChannelService.selectChannels(data);
        }else{
            finalFileName = KeyWords.EXPORT_ASSET_NAME;
            list = assetChannelService.selectChannels(data);
            list.forEach((e)->{
                e.setProductionName(e.getProducts().get(0).getProductionName());
            });
        }

        ExcelUtil<CapitalChannelEntity> util = new ExcelUtil<> (CapitalChannelEntity.class);
        util.exportExcel(response,list,finalFileName);
    }

    public static boolean isContainChinese(String str) {
        Pattern p = Pattern.compile("[\u4e00-\u9fa5]");
        Matcher m = p.matcher(str);
        if (m.find()) {
            return true;
        }
        return false;
    }
}
